var isIos
// #ifdef APP-PLUS
isIos = (plus.os.name == "iOS")
// #endif
const CryptoJS = require('./crypto-js.min.js')

function forMatNum(num) {
	return num < 10 ? '0' + num : num + '';
}

function initDays(year, month) {
	let totalDays = new Date(year, month, 0).getDate();
	let dates = [];
	for (let d = 1; d <= totalDays; d++) {
		dates.push(forMatNum(d));
	};
	return dates;
}

function initPicker(start, end, mode = "date", step) {
	let initstartDate = new Date(start);
	let endDate = new Date(end);
	let startYear = initstartDate.getFullYear();
	let startMonth = initstartDate.getMonth();
	let endYear = endDate.getFullYear();
	let years = [],
		months = [],
		days = [],
		hours = [],
		minutes = [],
		seconds = [];
	let totalDays = new Date(startYear, startMonth, 0).getDate();
	for (let s = startYear; s <= endYear; s++) {
		years.push(s + '');
	};
	for (let m = 1; m <= 12; m++) {
		months.push(forMatNum(m));
	};
	for (let d = 1; d <= totalDays; d++) {
		days.push(forMatNum(d));
	}
	for (let h = 0; h < 24; h++) {
		hours.push(forMatNum(h));
	}
	for (let m = 0; m < 60; m += step * 1) {
		minutes.push(forMatNum(m));
	}
	for (let s = 0; s < 60; s++) {
		seconds.push(forMatNum(s));
	}
	switch (mode) {
		case "date":
			return {
				years,
				months,
				days
			}
			break;
		case "yearMonth":
			return {
				years,
				months
			}
			break;
		case "dateTime":
			return {
				years,
				months,
				days,
				hours,
				minutes,
				seconds
			}
			break;
		case "time":
			return {
				hours,
				minutes,
				seconds
			}
			break;
	}
}

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

function getBaseUrl() {
	let BaseUrl;
	uni.getStorage({
		key: 'baseUrl',
		success: function(res) {
			BaseUrl = res.data;
		}
	});
}
// 获取今天的日期
function getToDay() {
	const date = new Date();
	let year = date.getFullYear();
	let month = date.getMonth() + 1;
	let day = date.getDate();
	month = month > 9 ? month : '0' + month;;
	day = day > 9 ? day : '0' + day;
	return `${year}-${month}-${day}`;
}
// 获取今天的日期时间
function getToDateTime() {
	const date = new Date();
	let year = date.getFullYear();
	let month = date.getMonth() + 1;
	let day = date.getDate();

	let h = date.getHours();
	let m = date.getMinutes();
	let s = date.getSeconds();

	month = month > 9 ? month : '0' + month;;
	day = day > 9 ? day : '0' + day;
	h = h > 9 ? h : '0' + h;
	m = m > 9 ? m : '0' + m;
	s = s > 9 ? s : '0' + s;
	return `${year}-${month}-${day} ${h}:${m}:${s}`;
}

// 获取多少天后的日期
function GetDateAfter(AddDayCount) {
	var AddDayCount = parseInt(AddDayCount);
	var dd = new Date();
	dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期 
	var y = dd.getFullYear();
	var m = dd.getMonth() + 1; //获取当前月份的日期 
	var d = dd.getDate();

	function checkT(s) {
		return s < 10 ? '0' + s : s;
	}
	return y + "-" + checkT(m) + "-" + checkT(d);
}


// 身份证号验证
var aCity = {
	11: "北京",
	12: "天津",
	13: "河北",
	14: "山西",
	15: "内蒙古",
	21: "辽宁",
	22: "吉林",
	23: "黑龙江",
	31: "上海",
	32: "江苏",
	33: "浙江",
	34: "安徽",
	35: "福建",
	36: "江西",
	37: "山东",
	41: "河南",
	42: "湖北",
	43: "湖南",
	44: "广东",
	45: "广西",
	46: "海南",
	50: "重庆",
	51: "四川",
	52: "贵州",
	53: "云南",
	54: "西藏",
	61: "陕西",
	62: "甘肃",
	63: "青海",
	64: "宁夏",
	65: "新疆",
	71: "台湾",
	81: "香港",
	82: "澳门",
	91: "国外"
}

function isCardID(sId) {
	var iSum = 0;
	var info = "";
	if (!/^\d{17}(\d|x)$/i.test(sId)) return "身份证长度或格式错误";
	sId = sId.replace(/x$/i, "a");
	if (aCity[parseInt(sId.substr(0, 2))] == null) return "身份证地区非法";
	var sBirthday = sId.substr(6, 4) + "-" + Number(sId.substr(10, 2)) + "-" + Number(sId.substr(12, 2));
	var d = new Date(sBirthday.replace(/-/g, "/"));
	if (sBirthday != (d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate())) return "身份证上的出生日期非法";
	for (var i = 17; i >= 0; i--) iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11);
	if (iSum % 11 != 1) return "身份证号非法";
	//aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女");//此次还可以判断出输入的身份证号的人性别
	return true;
}
// 手机号验证
function isMobile(tel) {
	var regex = /0?(13|14|15|17|18|19)[0-9]{9}/;
	if (!regex.test(tel)) return "手机号格式错误！";
	return true;
}
// 中文姓名验证
function isChines(name) {
	var regex = /[\u4e00-\u9fa5]/;
	if (!regex.test(name)) return false;
	return true;
}
// 车牌号验证
function isCarNumber(car) {
	var result = false;
	if (car.length == 7) {
		var regex = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;
		result = regex.test(car);
	}
	return result;
}
// 验证正整数
function isInteger(e) {
	var regex = /^[1-9]\d*$/;
	if (!regex.test(e)) {
		return false;
	} else {
		return true;
	}
}
// 大于= 0的数字，包含小数
function isIntNum(e) {
	var regex = /^[0-9]\d*(\.\d+)?$/;
	if (!regex.test(e)) {
		return false;
	} else {
		return true;
	}
}
// 判断参数是否已经存在数组内      存在false   不存在true
function checkArray(e, Arrays) {
	let flag = true;
	for (let i in Arrays) {
		if (e == Arrays[i]) {
			return false;
		}
	}
	return flag;
}

function hideBirthday(e) {
	var idcard = '';
	if (e) {
		idcard = e.replace(/^(.{6})(?:\d+)(.{4})$/, "$1****$2");
	}
	return idcard;
}

// 获取表单数据  
function getValueByclass(getVal, getHtm) {
	let myobject = {};
	if (getVal) {
		let formID = document.getElementsByClassName(getVal);
		for (var i = 0; i < formID.length; i++) {
			let oneId = formID[i].id;
			myobject[oneId] = document.getElementById(oneId).value;
		}
	}
	if (getHtm) {
		let formID2 = document.getElementsByClassName(getHtm);
		for (var i = 0; i < formID2.length; i++) {
			let oneId2 = formID2[i].id;
			myobject[oneId2] = document.getElementById(oneId2).innerHTML;
		}
	}
	return myobject;
}

// 采购权限校验
function checkMenu(e, list) {
	let s = true;
	if (list.indexOf(e) < 0) {
		uni.showToast({
			icon: 'none',
			title: '您的账户无操作权限！'
		})
		s = false;
	}
	return s;
}

function delayBack() {
	setTimeout(function() {
		uni.navigateBack({})
	}, 1500)
}

function mShowLoading() {
	setTimeout(() => {
		uni.showLoading({
			title: '加载中...',
			mask: true
		})
	}, 500)
}

function mHideLoading() {
	setTimeout(function() {
		uni.hideLoading();
	}, 500)
}

function tips(err) {
	uni.showToast({
		title: err,
		time:2500,
		icon: 'none'
	})
}

function setPageTitle(d) {
	uni.setNavigationBarTitle({
		title: d
	});
}

// 图片上传
function uploadImg( callback) {
	let baseUrl = getApp().globalData.BaseURL
	let Token =  getApp().globalData.Token ;
	uni.chooseImage({
		count: 1,
		success: (chooseImageRes) => {
			const tempFilePaths = chooseImageRes.tempFilePaths;
			// console.log(tempFilePaths);
			uni.uploadFile({
				url: baseUrl + '/api/appCommon/Upload',
				filePath: tempFilePaths[0],
				header: { Authorization:'BasicAuth '+Token },
				name: 'file',
				success: (uploadFileRes) => {
					console.log( 'uploadImg66' , uploadFileRes);
					let res = JSON.parse(uploadFileRes.data)
					if (uploadFileRes.statusCode == 200) {
						let imgUrlArr = baseUrl + res.Result[0];
						callback(imgUrlArr);
					} else {
						tips('图片上传失败');
					}
				}
			});
		}
	});
}
// 图片查看 传图片地址
function previewImage(imageList) {
	uni.previewImage({
		current: 0,
		urls: [imageList]
	})
}

function ajax() {

}

// 扫码获取 仓库，货位，物资 等信息
function Scan(URL, callback, id = '') {
	uni.scanCode({
		onlyFromCamera: true,
		success: res => {
			// console.log("扫描", res);
			if (res.scanType != "QR_CODE") {
				return uni.showToast({
					icon: "none",
					title: "类型错误，请重新扫描"
				});
			}
			GetDataByScan(URL, res.result, id, callback, );
		},
		fail: err => {
			console.log("扫描失败::", err);
		}
	});
}

function GetDataByScan(URL, code, id, callback) {
	uni.showLoading({
		title: "加载中..."
	});
	let Token =  getApp().globalData.Token ;
	let BS =  getApp().globalData.BaseURL ;
	let OKURL = URL.includes('http')?URL: BS+URL;
	console.log(99,BS+URL, code, id,Token);
	uni.request({
		url: OKURL,
		method: "POST",
		data: {
			Code: code,
			BILLNO: id
		},
		header: { Authorization:'BasicAuth '+Token },
		success: res => {
			// console.log("扫码数据", res);
			uni.hideLoading();
			if (res.data.IsSuccess != true) {
				uni.showToast({
					title: '失败：'+res.data.Message,
					icon: "none",
					duration: 3000
				});
			} else {
				let obj = res.data.Result;
				callback(obj)
			}
		}
	});
}

// 单独获取推荐货位 根据数量

function getRecommend(URL, data, callback) {
	let query = {
		"category": "",
		"page": 1,
		"rows": "50",
		"sidx": "",
		"sord": "",
		"queryJson": JSON.stringify(data),
		"userId": data.userId,
		"account": data.account
	}
	let Token =  getApp().globalData.Token ;
	console.log( '单独获取推荐货位' , query);
	// console.log(query);
	URL = getApp().globalData.BaseURL + URL
	console.log(URL);
	uni.request({
		url: URL,
		method: "POST",
		data: query,
		header: { Authorization:'BasicAuth '+Token },
		success: res => {
			console.log( '单独获取推荐货位' , res.data);
			if (res.data.IsSuccess != true) {
				uni.showToast({
					title: '未获取到推荐货位：' + res.data.Message,
					icon: "none",
					duration: 2000
				});
			} else {
				let obj = res.data.Result;
				// console.log("扫码数据", obj);
				callback(obj)
			}
		},
		error: error=> {
			console.log( '444' ,error );
		}
	});
}


// 获取url 后面的参数 
function getUrlParamteter(url) {
	let reg = /([^&?=]+)=([^&?=]+)/g,
		obj = {};
	url.replace(reg, function() {
		obj[arguments[1]] = arguments[2];
	})
	return obj;
}


function openScanUtils(id, index, callback) {
	// _isActiveStore = true ;
	// console.log(id,index)
	uni.scanCode({
		onlyFromCamera: true,
		success: function(res) {
			console.log(res);
			if (res.scanType != "QR_CODE") {
				return uni.showToast({
					icon: "none",
					title: "类型错误，请重新扫描"
				});
			}
			callback(res.result);
		}
	});
}

function mapSattionName(data) {
	if (!data) return [];
	let arr = JSON.parse(data);
	return arr;
}
// 获取更新
function handleUpdate(baseUrl, token = '') {
	let version = plus ? plus.runtime.version : '0';
	let dcType = plus.os.name == 'iOS' ? 2 : 0;
	let URL = baseUrl + '/api/SystemCenter/UpdateVersion';
	// console.log(URL, dcType);
	let Token =  getApp().globalData.Token ;
	uni.request({
		url: URL,
		data: {
			VERTYPE: dcType
		},
		method: 'POST',
		header: {
			Authorization: 'BasicAuth ' + token
		},
		success: function(res) {
			// console.log(JSON.stringify(res));
			if (res.statusCode == 200 && res.data.IsSuccess) {
				// console.log(JSON.stringify(res));
				let result = res.data.Result[0];
				if(!result) return;
				let titles = '请更新该版本！';
				let openUrl = baseUrl + '/' + result.VERURL;
				// let openUrl = 'http://121.28.141.37:8001/APK/SG1.11.190225.apk';
				let message = result.VERMEMO || "更新说明";
				let newVersion = result.VCODE;
				let ISUPDATE = result.ISUPDATE ; // 强制更新
				if (newVersion != version) {
					updateApp(openUrl, message, titles,ISUPDATE)
				} else {
					utils.speak('您已经是最新版本')
					return uni.showToast({
						title: '您已经是最新版本',
						icon: 'none'
					})
				}
			}
		}
	})
}

function updateApp(downUrl, message, titles,ISUPDATE) {
	// console.log(downUrl,message,titles)
	uni.showModal({ //提醒用户更新  
		title: titles,
		showCancel: true,
		content: message,
		success: (res) => {
			if (res.confirm) {
				let iosURL = 'https://apps.apple.com/cn/app/id1477792996';
				if (plus.os.name == 'iOS') {
					return plus.runtime.openURL(iosURL);
				}
				uni.showLoading({
					title: '下载中...',
					mask: true
				})
				// plus.runtime.openURL(downUrl);
				console.log(downUrl)
				var dtask = plus.downloader.createDownload(downUrl, {}, function(d, status) {
					// 下载完成 
					console.log(d, status)
					if (status == 200) {
						uni.hideLoading();
						plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename), {}, {}, function(error) {
							uni.showToast({
								title: '安装失败',
								mask: false,
								duration: 1500
							});
						})
					} else {
						uni.showToast({
							title: '更新失败',
							mask: false,
							duration: 1500
						});
					}
				});
				dtask.start();
			}else if(ISUPDATE==1){
				console.log(ISUPDATE);
				plus.runtime.quit();
			}
		}
	})
}

function LableSet(content) {
	// console.log(content);
	//制作标签格式， 
	var data = []; //定义一个数组
	var line = {}; //每添加一个，代表一行字

	//设置标签纸大小
	line = {};
	line.width = 40; //mm
	line.height = 30; //mm
	line.gap = 3; //标签纸之间，间隙长度 mm
	line.page = content.number || 1 ; //打印几份
	data.push(line); //每添加一个，代表一行字
	
	//添加 物资名称 
	line = {};
	line.text = content.name; 
	line.rotation = 90;
	line.x = 310;
	line.y = 30;
	line.xscal = 1;
	line.yscal = 1;
	data.push(line); //每添加一个，代表一行字
	//添加型号
	line = {};
	line.text = content.type; 
	line.rotation = 90;
	line.x = 280;
	line.y = 30;
	line.xscal = 1;
	line.yscal = 1;
	data.push(line); //每添加一个，代表一行字
	
	//添加物资条码
	line = {};
	line.text = content.bcode; 
	line.rotation = 90;
	line.x = 250;
	line.y = 30;
	line.xscal = 1;
	line.yscal = 1;
	data.push(line); //每添加一个，代表一行字

	// 加入二维码
	line = {};
	line.qrcode = content.qcode ;
	line.x = 50;
	line.y = 30;
	line.width = 6
	line.rotation = 0;
	data.push(line);
	// console.log(data);
	return data;
}

// 判断蓝牙是否开启 

function isOpenBlue(callback){
	uni.openBluetoothAdapter({
	  success(res) {
			callback();
			// console.log(res);
	  //   tips('请先开启蓝牙功能');
	  },
		fail(e){
			if(e.errCode=10001){
				uni.showModal({ //提醒用户更新
					title: '提示',
					showCancel: true,
					content: '如果您需要使用打印功能，请您先开启蓝牙。',
					success: (res) => {
						if (res.confirm) {
							gotoAppPermissionSetting()
						}
					},
				})
			}
			
			console.log(e);
		}
	})
}

// 跳转到**应用**的权限页面
function gotoAppPermissionSetting() {
	if (isIos) {
		var UIApplication = plus.ios.import("UIApplication");
		var application2 = UIApplication.sharedApplication();
		var NSURL2 = plus.ios.import("NSURL");
		var setting2 = NSURL2.URLWithString("app-settings:");
		application2.openURL(setting2);
		plus.ios.deleteObject(setting2);
		plus.ios.deleteObject(NSURL2);
		plus.ios.deleteObject(application2);
	} else {
		console.log(plus.device.vendor);
		var Intent = plus.android.importClass("android.content.Intent");
		var Settings = plus.android.importClass("android.provider.Settings");
		var Uri = plus.android.importClass("android.net.Uri");
		var mainActivity = plus.android.runtimeMainActivity();
		var intent = new Intent();
		intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
		var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
		intent.setData(uri);
		mainActivity.startActivity(intent);
	}
}
// url 传参 是特殊字符串的处理  % # 
function URIErroeTo(data){
	let aa = data.replace(/%/g, '%25') ;
	aa = aa.replace(/\#/g, '%23') 
	aa = aa.replace(/\&/g, '%26')
	aa = aa.replace(/\+/g, '%2B') 
	aa = aa.replace(/\=/g, '%3D') 
	aa = aa.replace(/\?/g, '%3F') 
	return aa ;
}

// function aesJmEncrypt(text) {
// 	var aseKey = "\x65\x6f\x73\x69\x6e\x65\x63\x6f\x6d\x65\x6f\x73\x69\x6e\x65\x63\x6f\x6d\x65\x6f\x73\x69\x6e\x65\x63\x6f\x6d\x65\x6f\x73\x69\x6e";
// 	var encrypt = CryptoJS.AES.encrypt(text, CryptoJS.enc.Utf8.parse(aseKey), {
// 		mode: CryptoJS.mode.ECB,
// 		padding: CryptoJS.pad.Pkcs7
// 	}).toString();
// 	return encrypt;
// }

function aesJmEncrypt(text) {
    var aseKey = "\x65\x6f\x73\x69\x6e\x65\x63\x6f\x6d\x65\x6f\x73\x69\x6e\x65\x63\x6f\x6d\x65\x6f\x73\x69\x6e\x65\x63\x6f\x6d\x65\x6f\x73\x69\x6e";
    var encrypt = CryptoJS.AES.encrypt(text, CryptoJS.enc.Utf8.parse(aseKey), {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    }).toString();
    return encrypt;
}

function showTips(msg){
	uni.showToast({
		title: msg,
		icon: 'none',
		duration: 2000
	});
}

function getExNumName(arr,id){
	if(Array.isArray(arr)){
		let a = arr.filter(i=>{
			return i.ItemValue == id
		})
		if(a.length) {
			return a[0].ItemName
		}else{
			return ''
		}
		
	}
}

module.exports = {
	formatTime: formatTime,
	formatLocation: formatLocation,
	dateUtils: dateUtils,
	getToDay,
	getToDateTime,
	GetDateAfter,
	isCardID,
	isMobile,
	hideBirthday,
	checkArray,
	isIntNum,
	isInteger,
	isCarNumber,
	isMobile,
	isChines,
	getValueByclass,
	initDays,
	initPicker,
	checkMenu,
	delayBack,
	tips, // 错误提示
	mShowLoading,
	mHideLoading,
	setPageTitle,
	uploadImg,
	previewImage,
	Scan,
	getUrlParamteter,
	openScanUtils,
	mapSattionName,
	getRecommend,
	handleUpdate, // 版本更新
	LableSet, // 打印标签内容设置
	isOpenBlue, // 蓝牙功能 开启判断
	URIErroeTo,
	aesJmEncrypt,
	showTips,
	getExNumName
}
